package com.mac;

import java.util.Locale;

public class MacDemo {

	public static void main(String[] args) {
		String macStr = "E7F27A01004B1200";
		System.out.println(isMac_0_9_A_F(macStr));

		String macStringWithColon = getMacStringWithColon(macStr);
		System.out.println(macStringWithColon);
	}

	/**
	 * <br>"E7F27A01004B1200" --> "E7:F2:7A:01:00:4B:12:00"
	 * <br>获取带“：”的ＭＡＣ地址字符串
	 * @param macStr
	 * @return 返回大写的E7:F2:7A:01:00:4B:12:00, Local.ENGLISH
	 */
	public static String getMacStringWithColon(String macStr) {
		if(isMacLengthWithNoColon(macStr, 16)) {
			StringBuilder sb = new StringBuilder(128);
			int startPosition = 0;
			sb.append(macStr.substring(startPosition, startPosition+=2)).append(":");
			sb.append(macStr.substring(startPosition, startPosition+=2)).append(":");
			sb.append(macStr.substring(startPosition, startPosition+=2)).append(":");
			sb.append(macStr.substring(startPosition, startPosition+=2)).append(":");
			sb.append(macStr.substring(startPosition, startPosition+=2)).append(":");
			sb.append(macStr.substring(startPosition, startPosition+=2)).append(":");
			sb.append(macStr.substring(startPosition, startPosition+=2)).append(":");
			sb.append(macStr.substring(startPosition, startPosition+=2));
			return sb.toString().toUpperCase(Locale.ENGLISH);
		}
		return null;
	}

	/**
	 * Returns true if Mac's String is 8
	 * @param macStr
	 * @return
	 */
	private static boolean isMacLengthWithNoColon(String macStr, int length){
		if(isEmpty(macStr) && macStr.length() != length && !macStr.contains(":")) {
			return false;
		} else {
			return isMac_0_9_A_F(macStr);
		}
	}

	/**
	 * 利用正则表达式判断是否符合mac地址形式
	 * @param macStr
	 * @param length
	 * @return
	 */
	public static boolean isMac_0_9_A_F(String macStr){
		String regex = "[A-Fa-f0-9]{16}";
		return macStr.matches(regex);
	}


	/**
	 * Returns true if the string is null or 0-length.
	 * @param str the string to be examined
	 * @return true if str is null or zero length
	 */
	public static boolean isEmpty(CharSequence str) {
		if (str == null || str.length() == 0)
			return true;
		else
			return false;
	}
}
